package me.zhengjie.modules.quartz.task.count;

import com.qiaofang.applet.service.other.domain.Corporation;
import com.qiaofang.applet.service.other.service.CityCompanyService;
import com.qiaofang.applet.service.other.service.CorporationService;
import com.qiaofang.applet.service.other.service.dto.CityCompanyDto;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.modules.quartz.service.dto.SyncCommon;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
public abstract class CountTaskBase {

    @Autowired
    private CorporationService corporationService;

    @Autowired
    private CityCompanyService cityCompanyService;

    public void corporationPullTask() {
        log.info("---开始执行");
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("deleted", match -> match.exact())
                .withIgnoreNullValues();
        Corporation corporation = new Corporation();
        corporation.setDeleted(Boolean.FALSE);
        Iterable<Corporation> list = corporationService.findAll(Example.of(corporation, matcher));
        list.forEach(item -> {
            List<CityCompanyDto> cityCompanyDtoList = cityCompanyService.getCompanyList(item.getCorporationCode());
            if (null == cityCompanyDtoList) {
                return;
            }
            cityCompanyDtoList.stream().forEach(cityCompanyDto -> {
                if (cityCompanyDto.getStatus() == 1) {
                    pullCityCompany(item, cityCompanyDto);
                }
            });
        });
        log.info("---执行完毕");
    }

    private void pullCityCompany(Corporation item, CityCompanyDto cityCompanyDto) {
        try {
            SyncCommon syncCommon = new SyncCommon();
            syncCommon.setCorporationCode(item.getCorporationCode());
            syncCommon.setAppId(item.getPullAppId());
            syncCommon.setAppKey(item.getPullAppKey());
            syncCommon.setDomain(item.getPullDomain());
            //具体公司信息
            syncCommon.setCityCode(cityCompanyDto.getCityCode());
            syncCommon.setCompanyUuid(cityCompanyDto.getCompanyUuid());
            //是否初始化
            syncCommon.setInit(cityCompanyDto.getInitFlag());
            count(syncCommon);
        } catch (Exception e) {
            log.error("pullCityCompany count error {}", e);
        }
    }

    protected abstract void count(SyncCommon syncCommon);
}
